package tool.zyk.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;
import tool.zyk.configuration.SimpleRpcConfiguration;
import tool.zyk.serializable.SerializableConverter;
import tool.zyk.serializable.SerializableFactory;
import tool.zyk.stardand.RpcProtocol;
import tool.zyk.stardand.RpcResponse;
import tool.zyk.utils.LogUtil;

import java.util.List;

/**
 * @author feite.zyk
 * @time 2024/2/1 13:39
 * @description
 */
@Slf4j
public class ProtocolResponseM2MEncoder extends MessageToMessageEncoder<RpcResponse> {
    private final SimpleRpcConfiguration simpleRpcConfiguration;

    public ProtocolResponseM2MEncoder(SimpleRpcConfiguration simpleRpcConfiguration) {
        super();
        this.simpleRpcConfiguration = simpleRpcConfiguration;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse, List<Object> list) throws Exception {
        try {
            log.debug("返回值协议包装:{}", rpcResponse);
            SerializableConverter serializableConverter = SerializableFactory.getSerializableConverter(simpleRpcConfiguration.getSerializableType());
            list.add(RpcProtocol.ofResponse(serializableConverter.parseTransferData2Object(rpcResponse), simpleRpcConfiguration.getSerializableType()));
        } catch (Throwable throwable) {
            LogUtil.printErrorLog(throwable);
            throw new RuntimeException(throwable);
        }
    }
}
